<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-button class="el-button--primary" @click="dialogFormVisible=true">添加角色</el-button>
      <!-- 添加角色-->
      <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
        <el-form :model="addrole">
          <el-form-item label="角色名称" label-width="120px">
            <el-input v-model="addrole.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" label-width="120px">
            <el-input v-model="addrole.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑角色-->
      <el-dialog title="编辑角色" :visible.sync="flag">
        <el-form :model="eait">
          <el-form-item label="角色名称" label-width="120px">
            <el-input v-model="eait.roleName" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色描述" label-width="120px">
            <el-input v-model="eait.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="flag = false">取 消</el-button>
          <el-button type="primary" @click="addbj">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 角色列表区域 -->
      <!-- row-key="id" 是2019年3月提供的新特性，
if there's nested data, rowKey is required.
      如果这是一个嵌套的数据，rowkey 是必须添加的属性-->
      <el-table row-key="id" :data="roleList" border>
        <!-- 添加展开列 -->
        <el-table-column type="expand"></el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="compile(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="del(scope.row.id)">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- {{scope.row}} -->
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二，三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限  -->
                <el-row
                  :class="[i2===0?'':'bdtop' ]"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分类权限的弹框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="setRightDialogClose"
      >
        <!-- @close="setRightDialogClose" -->
        <!-- 树形组件
        show-checkbox:显示复选框
        node-key:设置选中节点对应的值
        default-expand-all:是否默认展开所有节点
        :default-checked-keys 设置默认选中项的数组
        ref:设置引用-->
        <!-- 
        :data="rightsList"
        :props="treeProps"
         ref="treeRef"
         :default-checked-keys="defKeys"
        -->
        <el-tree
          :data="rightsList"
          :props="defaultProps"
          @node-click="handleNodeClick"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      roleList: [],
      // 添加角色
      addrole: {
        roleName: "",
        roleDesc: ""
      },
      //添加角色弹框
      dialogFormVisible: false,
      //编辑弹框
      flag: false,
      //编辑角色
      eait: {},
      // 分配权限的弹框
      setRightDialogVisible: false,
      //角色列表数据
      rightsList: [],
      //树形控件的属性绑定对象
      defaultProps: {
        //通过label设置树形节点文本展示authName
        children: "children",
        //设置通过children属性展示子节点信息
        label: "authName"
      },
      //设置树形控件中默认选中的内容
      defKeys: [],
      //保存正在操作的角色id
      roleId: ""
    };
  },
  methods: {
    //角色列表
    async getRoleList() {
      let { data: res } = await this.$http.get(`roles`);
      console.log(res.data);
      this.roleList = res.data;
    },
    // 点击确认添加角色
    async add() {
      let { data: res } = await this.$http.post("roles", this.addrole);
      console.log(res.data);
      this.dialogFormVisible = false;
      //   刷新页面
      this.getRoleList();
    },
    // 点击编辑回填数据
    compile(row) {
      // console.log(row);
      this.eait = row;
      //弹框显示
      this.flag = true;
    },
    // 点击确认修改内容
    async addbj() {
      let { data: res } = await this.$http.put(
        `roles/${this.eait.id}`,
        this.eait
      );
      console.log(res.data);
      if (res.meta.status != 200) {
        this.$message.error("修改用户失败");
      }
      //修改成功的提示
      this.$message.success("修改用户成功");
      //关闭弹框
      this.flag = false;
      // 刷新页面
      this.getRoleList();
    },
    // 点击删除
    del(id) {
      //弹窗提示用户是否要删除
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.$http.delete(`roles/${id}`).then(res => {
            //刷新页面
            this.getRoleList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 权限删除功能
    async removeRightById(role, rightId) {
      //弹窗提示用户是否要删除
      const confirmResult = await this.$confirm(
        "请问是否要删除该权限",
        "删除提示",
        {
          confirmButtonText: "确认删除",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != "confirm") {
        return this.$message.info("已经取消删除");
      }
      //用户点击了确定表示真的要删除
      //当发送delete请求之后，返回的数据就是最新的角色权限信息
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200)
        return this.$message.error("删除角色权限失败");
      //无需再重新加载所有权限
      // this.getRoleList();
      //把服务器返回的数据对现有的角色权限进行更新即可
      role.children = res.data;
    },
    // 分类权限的弹框
    async showSetRightDialog(role) {
      //将role.id保存起来以供保存权限时使用
      this.roleId = role.id;
      // 请求接口
      const { data: res } = await this.$http.get(`rights/tree`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限树失败");
      }
      //如果返回状态正常，将请求的数据保存在data中
      this.rightsList = res.data;
      //调用getLeafKeys进行递归，将三级权限添加到数组中
      this.getLeafKeys(role, this.defKeys);
      //当点击分配权限按钮时，展示对应的对话框
      this.setRightDialogVisible = true;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys数组中
    getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id);
      }
      //递归调用获取到最终的三级节点
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    setRightDialogClose() {
      //当用户关闭树形权限对话框的时候，清除掉所有选中状态
      this.defKeys = [];
    },
    // 点击确认按钮
    async allotRights() {
      // 获取所有选中及半选的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // 将数组转为拼接的字符串
      const idStr = keys.join(",");
      console.log(keys);

      // 发送请求完成更新
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败");

      this.$message.success("分配权限成功");
      this.getRoleList();
      // 弹框关闭
      this.setRightDialogVisible = false;
    },
    handleNodeClick(data) {
      console.log(data);
    }
  },
  mounted() {
    //刷新页面
    this.getRoleList();
  }
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 20px;
}
.el-button--primary {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  margin-bottom: 10px;
}
.bdbottom {
  border-bottom: solid 1px #eeeeee;
}
.bdtop {
  border-top: solid 1px #eeeeee;
}
.el-tag {
  margin: 7px;
}
</style>